﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebService.VO;
using WebService.BUS;
using System.Web.Security;

namespace WebService
{
    public partial class Login : System.Web.UI.Page
    {
        UserVO user;
        UserBUS userBUS;
        protected void Page_Load(object sender, EventArgs e)
        {
            userBUS = new UserBUS();
            user = new UserVO();
        }

        protected void btn_login_Click(object sender, EventArgs e)
        {
            user.Username = txt_user.Text.Trim();
            user.Password = Utility.MD5Hash(txt_password.Text.Trim());
            bool check = userBUS.login(user);
            if (check)
            {
                // Success, create non-persistent authentication cookie.
                FormsAuthentication.SetAuthCookie(
                        user.Username, false);

                FormsAuthenticationTicket ticket1 =
                   new FormsAuthenticationTicket(
                        1,                                   // version
                        user.Username,   // get username  from the form
                        DateTime.Now,                        // issue time is now
                        DateTime.Now.AddMinutes(10),         // expires in 10 minutes
                        false,      // cookie is not persistent
                        "Admin"                              // role assignment is stored
                    // in userData
                        );
                HttpCookie cookie1 = new HttpCookie(
                  FormsAuthentication.FormsCookieName,
                  FormsAuthentication.Encrypt(ticket1));
                Response.Cookies.Add(cookie1);

                // 4. Do the redirect. 
                String returnUrl1;
                // the login is successful
                if (Request.QueryString["ReturnUrl"] == null)
                {
                    returnUrl1 = "Admin/Default.aspx";
                }

                //login not unsuccessful 
                else
                {
                    returnUrl1 = Request.QueryString["ReturnUrl"];
                }
                Response.Redirect(returnUrl1);
            }
        }
    }
}